require(['init'], function () {

  function imgUpload($container) {
    var $uploadCoverBox = $container.find('.icon-uploadimg')
    var $uploadCoverThumb = $uploadCoverBox.find('img')
    var $uploadInput = $uploadCoverBox.find('input')

    var coverUploadInput = new UploadInput({
      $dom: $uploadInput,
      done: function (uploadImgSrc) {
        console.log(uploadImgSrc);
        var uploadImgFullSrc='/api/file?u=' + uploadImgSrc;

        if (uploadImgSrc) {
          $uploadCoverThumb.attr('src', uploadImgFullSrc);
          $uploadCoverBox.attr('data-value', uploadImgFullSrc);
          return;
        }
      }
    });
  }

  imgUpload($('#J_imgupload'))

  var id;
  ajaxMethod({
    url: '/api/agencys',
    success: function (data, status) {
      if(status.code == 0) {
        if(data.length) {
          id = data[0].id
          $('#J_img').attr('src', data[0].image)
          $('#J_text').val(data[0].text)
          if(data[0].status) {
            $('[name=use]').click()
          }
        }
      }
    }
  })

  $('#J_save').on('click', function () {
    var imgSrc = $('#J_img').attr('src')
    if(!imgSrc) {
      _Tips(i18next.t('table.uploadpictures'))//请上传图片
      return;
    }

    var data = {
      image: imgSrc,
      status: $('[name=use]').prop('checked') ? 1: 0,
      text: $('#J_text').val()
    }

    if(id !== undefined) {
      ajaxMethod({
        url: '/api/agency/'+id,
        method: 'put',
        data: data,
        success: function (data, status) {
          if(status.code == 0) {
            _Tips(i18next.t('info.savesuccessfully'))//保存成功
          }
        }
      })
    } else {
      ajaxMethod({
        url: '/api/agency',
        method: 'post',
        data: data,
        success: function (data, status) {
          if(status.code == 0) {
            _Tips(i18next.t('info.savesuccessfully'))//保存成功
          }
        }
      })
    }

  })

})
